package team.seekers.skill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;
import team.seekers.skill.common.utils.ParamCheckUtils;
import team.seekers.skill.common.utils.SkillUtils;
import team.seekers.skill.entity.dao.Chapter;
import team.seekers.skill.entity.dao.Section;
import team.seekers.skill.entity.query.ChapterQuery;
import team.seekers.skill.entity.vo.admin.add.AdminChapterAddVO;
import team.seekers.skill.entity.vo.admin.add.AdminSectionAddVO;
import team.seekers.skill.entity.vo.admin.list.AdminChapterListVO;
import team.seekers.skill.entity.vo.admin.update.AdminChapterUpdateVO;
import team.seekers.skill.result.Result;
import team.seekers.skill.result.ResultCode;
import team.seekers.skill.service.ChapterService;
import team.seekers.skill.entity.vo.fore.list.ChapterListVO;
import team.seekers.skill.service.SectionService;

import java.util.ArrayList;
import java.util.List;

import static team.seekers.skill.result.ResultCode.GET_FAIL;
import static team.seekers.skill.result.ResultCode.MAIN_GET_FAIL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hbc
 * @since 2021-01-18
 */
@RestController
@RequestMapping("/api/skill/chapter")
@Validated
public class ChapterController {

    @Autowired
    private ChapterService chapterService;
    @Autowired
    private SectionService sectionService;

    //学习页面渲染一个技能的所有章
    @GetMapping("/listChapterVOBySkillId/{skillId}")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result listChapterVOBySkillId(@PathVariable("skillId")String skillId) {
        if(ParamCheckUtils.isNotRightId(skillId)){
            return Result.fail(MAIN_GET_FAIL);
        }
        List<ChapterListVO> chapterListVos = chapterService.listChapterVOBySkillId(SkillUtils.getUserId(), skillId);
        if(chapterListVos == null){
            return Result.fail(GET_FAIL);
        }
        return Result.success("rows", chapterListVos);
    }

    //增加
    @PostMapping("/add")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result add(@RequestBody AdminChapterAddVO adminChapterAddVO){
        if(ParamCheckUtils.isNotRightId(adminChapterAddVO.getSkillId())){
            return Result.fail(ResultCode.PARAM_NOT_VALID).message("技能id无效");
        }
        Chapter chapter = new Chapter();
        BeanUtils.copyProperties(adminChapterAddVO,chapter);
        boolean save = chapterService.save(chapter);
        if (!save) {
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        List<AdminSectionAddVO> adminSectionAddVOList = adminChapterAddVO.getAdminSectionAddVOList();
        for (AdminSectionAddVO adminSectionAddVO : adminSectionAddVOList) {
            Section section = new Section();
            BeanUtils.copyProperties(adminSectionAddVO,section);
            section.setChapterId(chapter.getId());
            section.setSkillId(chapter.getSkillId());
            save = sectionService.save(section);
            if (!save) {
                return Result.fail(ResultCode.ACTION_FAIL);
            }
        }
        return Result.success();
    }

    //删除
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @DeleteMapping("/delete/{chapterId}")
    public Result delete(@PathVariable("chapterId") String chapterId){
        if (ParamCheckUtils.isNotRightId(chapterId)){
            return Result.fail(ResultCode.PARAM_NOT_VALID);
        }
        boolean delete = chapterService.delete(chapterId);
        if(!delete){
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        return Result.success();
    }


    //修改
    @PutMapping("/update")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result update(@RequestBody AdminChapterUpdateVO adminChapterUpdateVO){
        if(ParamCheckUtils.isNotRightId(adminChapterUpdateVO.getId())){
            return Result.fail(ResultCode.PARAM_NOT_VALID);
        }
        Chapter chapter = chapterService.getById(adminChapterUpdateVO.getId());
        BeanUtils.copyProperties(adminChapterUpdateVO,chapter);
        boolean b = chapterService.updateById(chapter);
        if(!b){
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        return Result.success();
    }


    //分页查询（标题模糊查询）
    @PostMapping("/pageNewsCondition/{current}/{limit}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result pageNewsCondition(@PathVariable("current") long current,
                                    @PathVariable("limit") long limit,
                                    @RequestBody ChapterQuery chapterQuery) {
        //创建page对象
        Page<Chapter> pageNews = new Page<>(current, limit);
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        String title = chapterQuery.getTitle();
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        String skillId = chapterQuery.getSkillId();
        if (!StringUtils.isEmpty(skillId)) {
            if(ParamCheckUtils.isNotRightId(skillId)){
                return Result.fail(ResultCode.PARAM_NOT_VALID);
            }
            wrapper.eq("skill_id", skillId);
            wrapper.orderByDesc("sequence");
        }
        String begin = chapterQuery.getBegin();
        if(!org.springframework.util.StringUtils.isEmpty(begin)){
            wrapper.ge("update_date",begin);
        }
        String end = chapterQuery.getEnd();
        if (!org.springframework.util.StringUtils.isEmpty(end)){
            wrapper.le("update_date",end);
        }
        //调用方法实现条件分页查询(按照章节排序的先后顺序)
        chapterService.page(pageNews, wrapper);
        long total = pageNews.getTotal();
        List<Chapter> records = pageNews.getRecords();
        if(records == null){
            return Result.fail(GET_FAIL);
        }
        List<AdminChapterListVO> voList = new ArrayList<>();
        for (Chapter record : records) {
            AdminChapterListVO chapterVo = new AdminChapterListVO();
            BeanUtils.copyProperties(record,chapterVo);
            voList.add(chapterVo);
        }
        return Result.success().data("total", total).data("rows", voList);
    }


}

